package com.lee.auth.security.filter;

import com.lee.auth.security.config.PathHandler;
import com.lee.common.exception.CustomException;
import lombok.AllArgsConstructor;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Lee HN
 * @date 2021/4/1 10:28
 */
@AllArgsConstructor
public class AuthenticationFilter implements Filter {

    private final PathHandler[] handlers;

    private final ResponseOutput responseOutput;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        for (PathHandler handler : handlers) {
            try { if (handler.handle(req, resp)) break; } catch (CustomException e) {
                responseOutput.failure(resp, e.getStatus(), e.getMessage());
                return;
            }
        }
        chain.doFilter(request, response);
    }

}
